/*
 * keyvaloper.c
 *
 *  Created on: Jan 14, 2014
 *      Author: jqc
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "config.h"
#include "keyvaloper.h"
#include "returnval.h"

#define DEBUG	(DEBUG_SWITCH && 1)

static void getNodePos(NODE *head, const char *key, NODE **pos)
{
	NODE *iter = head;

	if (DEBUG)
		fprintf(stderr, "[%s] find key : %s\n", __func__, key);

	while (NULL != iter->next) {
		if (TLINE_CONF == iter->next->data.type
				&& 0 == strcmp(iter->next->data.ctnt.conf.key, key)) {
			*pos = iter;
			if (DEBUG)
				fprintf(stderr, "[%s] type=%d, key=%s, value=%s\n", __func__,
						(*pos)->next->data.type, (*pos)->next->data.ctnt.conf.key,
						(*pos)->next->data.ctnt.conf.val);
			return;
		}
		iter = iter->next;
	}
	*pos = iter;
}

int confItemAdd(NODE *confmap, const CONFIGITEM *item)
{
	NODE *pos = NULL;

	if (DEBUG)
		fprintf(stderr, "[%s] key=%s, value=%s\n", __func__, item->key, item->val);

	getNodePos(confmap, item->key, &pos);
	if (NULL == pos->next) {
		NODE *node = (NODE*) malloc(sizeof(NODE));
		if (NULL == node) {
			fprintf(stderr, "[%s] malloc for add oper failed\n", __func__);
			return OPER_FAIL;
		}

		node->next = pos->next;
		pos->next = node;

		node->data.type = TLINE_CONF;
		strncpy(node->data.ctnt.conf.key, item->key, LEN_KEY_MAX);
		strncpy(node->data.ctnt.conf.val, item->val, LEN_VAL_MAX);
	} else
		strncpy(pos->next->data.ctnt.conf.val, item->val, LEN_VAL_MAX);

	return 0;
}

int confItemDel(NODE *confmap, const char *key)
{
	NODE *cur = NULL;
	NODE *pos = NULL;

	if (DEBUG)
		fprintf(stderr, "[%s] key=%s\n", __func__, key);

	getNodePos(confmap, key, &pos);
	if (NULL == pos->next) {
		fprintf(stderr, "[%s] can't find key %s\n", __func__, key);
		return OPER_NKEY;
	} else {
		cur = pos->next;
		pos->next = pos->next->next;
		cur->next = NULL;
		free(cur);
	}

	return 0;
}

int confItemMod(NODE *confmap, const CONFIGITEM *item)
{
	NODE *pos = NULL;

	if (DEBUG)
		fprintf(stderr, "[%s] key=%s, value=%s\n", __func__, item->key, item->val);

	getNodePos(confmap, item->key, &pos);
	if (NULL == pos->next) {
		fprintf(stderr, "[%s] can't find key %s\n", __func__, item->key);
		return OPER_NKEY;
	} else
		strncpy(pos->next->data.ctnt.conf.val, item->val, LEN_VAL_MAX);

	return 0;
}

int confItemQur(NODE *confmap, CONFIGITEM *item)
{
	NODE *pos = NULL;

	if (DEBUG)
		fprintf(stderr, "[%s] key=%s, value=%s\n", __func__, item->key, item->val);

	getNodePos(confmap, item->key, &pos);
	if (NULL == pos->next) {
		fprintf(stderr, "[%s] can't find key %s\n", __func__, item->key);
		return OPER_NKEY;
	} else
		strncpy(item->val, pos->next->data.ctnt.conf.val, LEN_VAL_MAX);

	return 0;
}
